package com.yanq.liancar.fragment;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.BindCarActivity;
import com.yanq.liancar.activity.BindOBDActivity;
import com.yanq.liancar.activity.CarDoctorActivity;
import com.yanq.liancar.activity.CarStatusActivity;
import com.yanq.liancar.activity.CuringAmdActivity;
import com.yanq.liancar.activity.DrivingBehaviorActivity;
import com.yanq.liancar.activity.LoginActivity;
import com.yanq.liancar.activity.MaintainActiviity;
import com.yanq.liancar.activity.MinUserMainActivity;
import com.yanq.liancar.activity.MyCarActivity;
import com.yanq.liancar.activity.OilFenxiActivity;
import com.yanq.liancar.activity.SmallCBuyVIPActivity;
import com.yanq.liancar.base.BaseLYFragment;
import com.yanq.liancar.base.BaseLazyFragment;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.FindOdbBindBean;
import com.yanq.liancar.bean.MileageBBean;
import com.yanq.liancar.bean.MileageBean;
import com.yanq.liancar.bean.ObdHomeDataBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.loginUserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.MyUtils;
import com.yanq.liancar.util.ToastUtil;
import com.yanq.liancar.util.ToastUtils;
import com.yanq.liancar.util.Utils;

import org.json.JSONArray;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class GuanjiaFragment extends BaseLazyFragment {
    @BindView(R.id.rl_top)
    RelativeLayout toolbar;
    @BindView(R.id.ll_cardoctor)
    LinearLayout carDoctor;
    @BindView(R.id.drive_xingwei)
    TextView driveXingwei;
    @BindView(R.id.tv_youhao)
    TextView youhao;
    @BindView(R.id.mycar)
    TextView mycar;
    @BindView(R.id.driving_day)
    TextView driving_day;
    @BindView(R.id.driving_FuelConsumption)
    TextView driving_FuelConsumption;
    @BindView(R.id.driving_TripMileage)
    TextView driving_TripMileage;
    @BindView(R.id.car_status)
    LinearLayout carStatus;
    @BindView(R.id.tv_curingAmd)
    TextView tv_curingAmd;
    @BindView(R.id.guanjia_scrollView)
    ScrollView mScrollView;
    @BindView(R.id.mapview)
    MapView mMapView;
    @BindView(R.id.tv_shengji)
    TextView tv_shengji;
    @BindView(R.id.tv_bind)
    TextView tv_bind;
    @BindView(R.id.guanjia_no_obd)
    RelativeLayout rl_no_obd;
    @BindView(R.id.tv_buyvip)
    TextView tv_buyvip;
    Unbinder unbinder;
    private String mUid = "";
    private AMap mAMap;
    //定义一个UiSettings对象
    private UiSettings mUiSettings;
    private LatLng markerPosition;
    private double Latitude, Longitude;
    private Marker marker;
    private int VipState, bindingOBD;
    @Override
    protected int setLayoutId() {
        return R.layout.fragment_guanjia;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ImmersionBar.with(mActivity).statusBarDarkFont(true).init();
        mMapView.onCreate(savedInstanceState);

        SpannableString spannableString = new SpannableString("升级VIP，获得超值服务");
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.background_content));
        spannableString.setSpan(colorSpan, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan3 = new ForegroundColorSpan(getResources().getColor(R.color.main_color));
        spannableString.setSpan(colorSpan3, 0, 5, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tv_buyvip.setText(spannableString);

        LogUtils.e("44444444444444444","1111111111111111");
    }

    @Override
    public void onResume() {
        super.onResume();
        ToastUtil.showProgressDialog(mActivity);
        mMapView.onResume();
        getOBDInfo();
        LogUtils.e("44444444444444444","22222222222222222");
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(mActivity).statusBarDarkFont(true).init();
    }

    //查询有没有绑定车辆
    private void getOBD() {
        OkGo.<String>get(Config.s + "llc/odbbind/findOdbBind")
                .tag(this)
                .params("token", UserBean.getcToken(mActivity))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("qeqweqe", response.body());
                        Gson gson = new Gson();
                        FindOdbBindBean info = gson.fromJson(response.body(), FindOdbBindBean.class);
                        if (info.isIsSuccess()) {
                            //rlNoOBD.setVisibility(View.GONE);
                            mScrollView.setVisibility(View.VISIBLE);
                            getOBDInfo();
                        } else {
                            if ("未绑定OBD".equals(info.getOutputMessage())) {
                                //rlNoOBD.setVisibility(View.VISIBLE);
                                mScrollView.setVisibility(View.GONE);
                            }
                        }
                    }
                });
    }

    //查询OBD信息
    private void getOBDInfo() {
        OkGo.<String>get(Config.s + "llc/odbcheck/queryObdHomeData")
                .tag(this)
                .params("token", UserBean.getcToken(mActivity))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("qeqweqe", response.body());
                        Gson gson = new Gson();
                        ObdHomeDataBean info = gson.fromJson(response.body(), ObdHomeDataBean.class);
                        if (info.isIsSuccess()) {
                            ToastUtil.dismissProgressDialog();

                            driving_TripMileage.setText(info.getData().getMileage());       //总里程
                            driving_day.setText(info.getData().getDay() + "");              //停驶天数
                            driving_FuelConsumption.setText(info.getData().getOilWear());   //油耗
                            Latitude = info.getData().getLatitude();
                            Longitude = info.getData().getLongitude();
                            VipState = info.getData().getVipState();           //是否是VIP
                            bindingOBD = info.getData().getBindingOBD();       //是否是绑定OBD
                            //                            //是否是VIP
                            //                            if (info.getData().getVipState() == 0) {
                            //                                tv_buyvip.setVisibility(View.VISIBLE);
                            //                            } else {
                            //                                tv_buyvip.setVisibility(View.GONE);
                            //                            }
                            //是否绑定obd
                            if (bindingOBD == 0) {
                                mScrollView.setVisibility(View.GONE);
                                rl_no_obd.setVisibility(View.VISIBLE);
                            } else {
                                mScrollView.setVisibility(View.VISIBLE);
                                rl_no_obd.setVisibility(View.GONE);
                            }
                            init();
                        } else {
                            ToastUtil.dismissProgressDialog();
                            mScrollView.setVisibility(View.GONE);
                            rl_no_obd.setVisibility(View.VISIBLE);
                            //                            if ("请先登录".equals(info.getOutputMessage())) {
                            //                                rl_noLogin.setVisibility(View.VISIBLE);
                            //                                rlNoOBD.setVisibility(View.GONE);
                            //                                mScrollView.setVisibility(View.GONE);
                            //                            } else {
                            //                                rl_noLogin.setVisibility(View.GONE);
                            //                                rlNoOBD.setVisibility(View.VISIBLE);
                            //                                mScrollView.setVisibility(View.GONE);
                            //                            }
                        }
                    }
                });
    }


    /**
     * 初始化AMap对象
     */

    private void init() {

        if (mAMap == null) {

            mAMap = mMapView.getMap();

            mUiSettings = mAMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);  //显示缩放按钮
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);

            markerPosition = new LatLng(Latitude, Longitude);
            mAMap.moveCamera(CameraUpdateFactory.changeLatLng(markerPosition));
            mAMap.moveCamera(CameraUpdateFactory.zoomTo(14));

        }

        addGrowMarker();

    }

    /**
     * 添加带生长效果marker
     */

    private void addGrowMarker() {

        MarkerOptions options = new MarkerOptions();

        options.position(markerPosition);

        options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(), R.mipmap.che)));

        marker = mAMap.addMarker(options);

        Animation markerAnimation = new ScaleAnimation(0, 1, 0, 1); //初始化生长效果动画

        markerAnimation.setDuration(1000);  //设置动画时间 单位毫秒

        marker.setAnimation(markerAnimation);


    }


    @OnClick({R.id.ll_cardoctor, R.id.drive_xingwei, R.id.tv_youhao, R.id.car_status, R.id.mycar, R.id.tv_curingAmd, R.id.tv_buyvip, R.id.tv_shengji, R.id.tv_bind})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.ll_cardoctor:         //车载医生

                startActivity(new Intent(getContext(), CarDoctorActivity.class));

                break;
            case R.id.drive_xingwei:        //驾驶行为

                startActivity(new Intent(getContext(), DrivingBehaviorActivity.class));

                break;
            case R.id.tv_youhao:            //油耗分析

                startActivity(new Intent(getContext(), OilFenxiActivity.class));

                break;
            case R.id.car_status:           //车辆状态

                Bundle bundle = new Bundle();
                bundle.putDouble("lat", Latitude);
                bundle.putDouble("lon", Longitude);
                RxActivityTool.skipActivity(mActivity, CarStatusActivity.class, bundle);

                break;
            case R.id.mycar:
                startActivity(new Intent(getContext(), MyCarActivity.class));
                break;
            case R.id.tv_curingAmd:

                //RxToast.success("该功能暂未开放");

                //startActivity(new Intent(getContext(), CuringAmdActivity.class));

                RxActivityTool.skipActivity(mActivity, MaintainActiviity.class);
                break;
            //            case R.id.tv_bangdingOBD:
            //                RxActivityTool.skipActivity(mActivity, BindOBDActivity.class);
            //                break;
            //            case R.id.tv_goLogin:
            //                RxActivityTool.skipActivity(mActivity, LoginActivity.class);
            //                break;
            case R.id.tv_buyvip:
                RxActivityTool.skipActivity(mActivity, SmallCBuyVIPActivity.class);
                break;
            case R.id.tv_bind:
                RxActivityTool.skipActivity(mActivity, MyCarActivity.class);
                break;
            case R.id.tv_shengji:
                RxActivityTool.skipActivity(mActivity, SmallCBuyVIPActivity.class);
                break;
        }
    }

    private void buyVipDialog() {
        final Dialog bottomDialog = new Dialog(getContext());
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_buyvip, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9);
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        TextView cancel = bottomDialog.findViewById(R.id.cancel);
        TextView submit = bottomDialog.findViewById(R.id.submit);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
                RxActivityTool.skipActivity(mActivity, SmallCBuyVIPActivity.class);
            }
        });

    }

    private void loginDialog() {
        final Dialog bottomDialog = new Dialog(getContext());
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_login, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9);
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.setCanceledOnTouchOutside(false);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        final EditText et_num = bottomDialog.findViewById(R.id.Account);
        final EditText et_password = bottomDialog.findViewById(R.id.Password);
        TextView tv_login = bottomDialog.findViewById(R.id.tv_login);
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*会员登录*/
                OkGo.<String>post(Config.s + "llc/loginUser")
                        .tag(this)
                        .params("tel", et_num.getText().toString().trim())
                        .params("password", et_password.getText().toString())
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Gson gson = new Gson();
                                loginUserBean bean = gson.fromJson(response.body(), loginUserBean.class);
                                if (bean.isIsSuccess()) {
                                    bottomDialog.dismiss();
                                    InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                                    // 隐藏软键盘
                                    imm.hideSoftInputFromWindow(mActivity.getWindow().getDecorView().getWindowToken(), 0);
                                    LogUtils.e("1111111", bean.getData().getToken());
                                    UserBean.setID(mActivity, bean.getData().getUser().getUid());
                                    RxSPTool.putString(mActivity, "UserPhone", bean.getData().getUser().getTel());
                                    UserBean.setcToken(mActivity, bean.getData().getToken());
                                    UserBean.setName(mActivity, bean.getData().getUser().getUsername());
                                    UserBean.setSign(mActivity, bean.getData().getUser().getSign());
                                    pushPhoneToken();
                                    getOBDInfo();
                                    RxToast.success(bean.getOutputMessage());
                                } else {
                                    RxToast.error(bean.getOutputMessage());
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                RxToast.error("服务器连接失败");
                                LogUtils.e("asdasdad", response.code() + "");
                                LogUtils.e("asdasdad", response.message() + "");
                                if (response.code() == -1) {   //服务器连接不成功

                                }

                                super.onError(response);
                            }
                        });

            }
        });

    }


    private void pushPhoneToken() {
        OkGo.<String>post(Config.s + "llc/pushController/addPushTokenForUser")
                .tag(this)
                .params("token", UserBean.getcToken(mActivity))
                .params("pushToken", UserBean.getPushToken(mActivity))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接失败");
                        LogUtils.e("asdasdad", response.code() + "");
                        LogUtils.e("asdasdad", response.message() + "");
                        super.onError(response);
                    }
                });
    }


}
